package cn.jsj.invite.aop.aspect;


import cn.jsj.invite.aop.StringParam;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class StringParamHandler implements ConstraintValidator<StringParam, String> {

    private boolean canBeNull;

    private boolean canContentSpace;

    private int maxLength;

    private int minLength;

    @Override
    public void initialize(StringParam constraintAnnotation) {
        this.canBeNull = constraintAnnotation.allowNull();
        this.canContentSpace = constraintAnnotation.allowSpace();
        this.maxLength = constraintAnnotation.maxLength();
        this.minLength = constraintAnnotation.minLength();
        if (minLength < 0) {
            minLength = 0;
        }
        if (maxLength < minLength) {
            maxLength = minLength;
        }
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null) {
            return canBeNull;
        }
        if (s.contains(" ")) {
            return canContentSpace;
        }
        if (s.length() < minLength) {
            return false;
        }
        return s.length() <= maxLength;
    }
}
